﻿$(function () {
    $("#contrast-dialog:ui-dialog").dialog("destroy");

    var value = $("#tbxContrastValue"),
			allFields = $([]).add(value),
			tips = $(".validateTips");

    function updateTips(t) {
        tips
				.text(t)
				.addClass("ui-state-highlight");
        setTimeout(function () {
            tips.removeClass("ui-state-highlight", 1500);
        }, 500);
    }

    function checkLength(o, n, min, max) {
        if (o.val().length > max || o.val().length < min) {
            o.addClass("ui-state-error");
            updateTips("Length of " + n + " must be between " +
    					min + " and " + max + ".");
            return false;
        } else {
            return true;
        }
    }

    function checkValueInRange(o, n, min, max) {
        if (o.val() < min || o.val() > max) {
            o.addClass("ui-state-error");
            updateTips("value of " + n + " must be between " + min + " and " + max + ".");
            return false;
        } else {
            return true;
        }
    }

    function checkRegexp(o, regexp, n) {
        if (!(regexp.test(o.val()))) {
            o.addClass("ui-state-error");
            updateTips(n);
            return false;
        } else {
            return true;
        }
    }

    $("#contrast-dialog-form").dialog({
        autoOpen: false,
        height: 210,
        width: 250,
        modal: true,
        buttons: {
            "Apply": function () {
                var bValid = true;
                allFields.removeClass("ui-state-error");
                bValid = bValid && checkValueInRange(value, "value", -255, 255)
                //bValid = bValid && checkLength(value, "value", 1, 4);
                bValid = bValid && checkRegexp(value, /^-?\d+$/, "value must be a number.");

                if (bValid) {
                    $("#history tbody").append("<tr>" +
                            "<td>" + "Contrast adjustment" + "</td>" +
							"<td>" + value.val() + "</td>" +
						    "</tr>");
                    document.getElementById("iframe").src = "ImageViewer.aspx?process=contrast" + "&&value=" + value.val();
                    $(this).dialog("close");
                    iFrameRefresh();
                }
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        },
        close: function () {
            allFields.val("").removeClass("ui-state-error");
        }
    });

    $("#contrast-adjustment")
			.button()
			.click(function () {
			    $("#contrast-dialog-form").dialog("open");
			});
});
	